/**
 * 类名：SearchAction
 * 创建日期： 2014-11-7 下午3:25:34
 * 
 */
package com.erms.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.erms.bean.Courseware;
import com.erms.bean.FileInfo;
import com.erms.bean.Homework;
import com.erms.bean.Message;
import com.erms.bean.StudentTeach;
import com.erms.bean.Task;
import com.erms.bean.Teach;
import com.erms.dao.CoursewareDAO;
import com.erms.dao.HomeworkDAO;
import com.erms.dao.MessageDAO;
import com.erms.dao.StudentTeachDAO;
import com.erms.dao.TaskDAO;
import com.erms.dao.TeachDAO;
import com.erms.util.StringUtil;

/**
 * @author hmb
 *         备注：
 * 
 */
public class SearchAction extends BaseAction {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 2577059654995854119L;

	private String				keyword;
	private String				type;

	private String				resultJson;
	@Resource
	private TaskDAO				taskDAO;
	public String getResultJson() {
	
		return resultJson;
	}

	public void setResultJson(String resultJson) {
	
		this.resultJson = resultJson;
	}

	@Resource
	private CoursewareDAO		coursewareDAO;
	@Resource
	private HomeworkDAO			homeworkDAO;
	@Resource
	private MessageDAO			messageDAO;
	@Resource
	private TeachDAO			teachDAO;
	@Resource
	private StudentTeachDAO		studentTeachDAO;

	private Map<String, String>	teachMap;
	private String				userID;
	private String				identity;

	public String getType() {

		return type;
	}

	public void setType(String type) {

		this.type = type;
	}

	public String getKeyword() {

		return keyword;
	}

	public void setKeyword(String keyword) {

		this.keyword = keyword;
	}

	/**
	 * @see com.erms.action.BaseAction#execute()
	 * @return
	 * @throws Exception
	 */
	@Override
	public String execute() throws Exception {

		// TODO 自动生成的方法存根
		// json字段如下:{error:
		// 0，msg:".."，data:[{name:"..",teachID:"..",teachName:"..",type:".."}{...}]}
		logger.debug("将执行搜索，关键字:"+keyword+";类型:"+type);
		JSONObject json = new JSONObject();
		if (StringUtil.isNull(keyword)) {
			json.put("error", 1);
			json.put("msg", "关键字为空");
			return SUCCESS;
		}
		userID = getUserNameFromSession();
		identity = getTypeFormSession();
		if (StringUtil.isNull(userID) || StringUtil.isNull(identity)) {
			json.put("error", 1);
			json.put("msg", "登录超时或未登录");
			return SUCCESS;
		}

		initTeachMap();

		List<Map<String, Object>> resultList = new ArrayList<>();
		if (StringUtil.isNull(type)) {
			type = "all";
		}
		switch (type) {
			case "task" :
				resultList = searchTask();
				break;
			case "homework" :
				resultList = searchHomework();
				break;
			case "message" :
				resultList = searchMessage();
				break;
			case "courseware" :
				resultList = searchCourseware();
				break;
			default :
				resultList = searchAll();
				break;
		}
		json.put("error", 0);
		json.put("data", JSONArray.fromObject(resultList).toString());
		resultJson = json.toString();
		logger.debug("请求结果:"+resultJson);
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	private void initTeachMap() {

		if (STUDENT.equals(identity)) {
			teachMap = new HashMap<>();
			List<StudentTeach> list = studentTeachDAO.findByProperty(
					"id.user.id", userID);
			int n = list.size();
			for (int i = 0; i < n; i++) {
				Teach teach = list.get(i).getId().getTeach();
				teachMap.put(teach.getId(), teach.getCourse().getName());
			}
		} else if (TEACHER.equals(identity)) {
			teachMap = new HashMap<>();
			List<Teach> list = teachDAO.findByTeacherId(userID);
			int n = list.size();
			for (int i = 0; i < n; i++) {
				Teach teach = list.get(i);
				teachMap.put(teach.getId(), teach.getCourse().getName());
			}
		}
	}

	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> searchTask() {

		List<Map<String, Object>> list = new ArrayList<>();
		Map<String, Object> map = null;
		Set<String> set = teachMap.keySet();
		for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
			String teachID = iterator.next();
			List<Task> tasks = taskDAO.findByProperty("teach.id", teachID);
			for (int i = 0; i < tasks.size(); i++) {
				Task task = tasks.get(i);
				String title = task.getTitle();
				String content = task.getContent();
				FileInfo fileInfo = task.getFileInfo();
				if ((!StringUtil.isNull(title) && title.contains(keyword))
						|| (!StringUtil.isNull(content) && content
								.contains(keyword))
						|| (fileInfo != null && fileInfo.getName().contains(
								keyword))) {
					map = new HashMap<>();
					map.put("id", task.getId());
					map.put("teachID", teachID);
					map.put("teachName", teachMap.get(teachID));
					map.put("name", title);
					map.put("type", "task");
					map.put("content", content);
					if (fileInfo != null) {
						map.put("fileID", fileInfo.getId());
						String fileName = fileInfo.getName();
						int a = fileName.lastIndexOf("_");
						int b = fileName.lastIndexOf(".");
						if (a > 0 && b > 0) {
							fileName = fileName.substring(0, a)
									+ fileName.substring(b);
						}
						map.put("fileName", fileName);
					} else {
						map.put("fileID", -1);
						map.put("fileName", "无");
					}
					list.add(map);

				}

			}

		}

		return list;
	}

	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> searchCourseware() {
		logger.debug("搜索课件");
		List<Map<String, Object>> list = new ArrayList<>();
		Set<String> set = teachMap.keySet();
		Map<String, Object> map = null;
		for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
			String teachID = iterator.next();
			List<Courseware> coursewares = coursewareDAO.findByProperty(
					"teach.id", teachID);
			for (Courseware courseware : coursewares) {
				FileInfo fileInfo = courseware.getFileInfo();
				if (fileInfo == null) {
					continue;
				}
				String fileName = fileInfo.getName();
				int a = fileName.lastIndexOf("_");
				int b = fileName.lastIndexOf(".");
				if (a > 0 && b > 0) {
					fileName = fileName.substring(0, a)
							+ fileName.substring(b);
				}
				if (!StringUtil.isNull(fileName) && fileName.contains(keyword)) {
					map = new HashMap<>();
					map.put("id", courseware.getId());
					map.put("teachID", teachID);
					map.put("teachName", teachMap.get(teachID));
					map.put("type", "courseware");
					map.put("fileID", fileInfo.getId());					
					map.put("fileName", fileName);
					list.add(map);
				}
			}
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> searchHomework() {
		logger.debug("搜索提交的作业");
		List<Map<String, Object>> list = new ArrayList<>();
		Map<String, Object> map = null;
		List<Homework> homeworks = homeworkDAO
				.findByProperty("user.id", userID);
		for (Homework homework : homeworks) {
			FileInfo fileInfo = homework.getFileInfo();
			String content = homework.getContent();
			String fileName = "";
			if (fileInfo != null) {
				fileName = fileInfo.getName();
				int a = fileName.lastIndexOf("_");
				int b = fileName.lastIndexOf(".");
				if (a > 0 && b > 0) {
					fileName = fileName.substring(0, a) + fileName.substring(b);
				}
			}
			if ((!StringUtil.isNull(content) && content.contains(keyword))
					|| (fileName.contains(keyword))) {
				map = new HashMap<>();
				map.put("id", homework.getId());
				map.put("content", content);
				map.put("type", "homework");
				if (fileInfo != null) {
					map.put("fileID", fileInfo.getId());
					map.put("fileName", fileName);
				} else {
					map.put("fileID", -1);
					map.put("fileName", "无");
				}
				list.add(map);
			}
		}

		return list;
	}

	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> searchMessage() {
		logger.debug("搜索通知");
		List<Map<String, Object>> list = new ArrayList<>();
		Map<String, Object> map = null;
		Set<String> set = teachMap.keySet();
		for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
			String teachID = iterator.next();
			List<Message> messages = messageDAO.findByProperty("teach.id",
					teachID);
			for (Message message : messages) {
				String title = message.getTitle();
				String content = message.getContent();
				String fileName = "";
				FileInfo fileInfo = message.getFileInfo();
				if (fileInfo != null) {
					fileName = fileInfo.getName();
					int a = fileName.lastIndexOf("_");
					int b = fileName.lastIndexOf(".");
					if (a > 0 && b > 0) {
						fileName = fileName.substring(0, a)
								+ fileName.substring(b);
					}
				}
				if ((!StringUtil.isNull(title) && title.contains(keyword))
						|| (!StringUtil.isNull(content)
								&& content.contains(keyword) || fileName
									.contains(keyword))) {
					map = new HashMap<>();
					map.put("id", message.getId());
					map.put("teachID", teachID);
					map.put("teachName", teachMap.get(teachID));
					map.put("name", title);
					map.put("type", "message");
					map.put("content", content);
					if (fileInfo != null) {
						map.put("fileID", fileInfo.getId());
						map.put("fileName", fileName);
					}else {
						map.put("fileID", -1);
						map.put("fileName", "无");
					}
					list.add(map);
				}
			}
		}
		return list;
	}

	private List<Map<String, Object>> searchAll() {

		List<Map<String, Object>> list = new ArrayList<>();
		list.addAll(searchCourseware());
		list.addAll(searchHomework());
		list.addAll(searchMessage());
		list.addAll(searchTask());

		return list;
	}
}
